package com.utilities.template;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SimpleTemplateEl {

    private final Pattern pattern = Pattern.compile("\\$\\{(\\w+)\\}");

    private String template;

    public SimpleTemplateEl(String template) {
        this.template = template;
    }

    public String render(Map<String, Object> data) {
        Matcher m = pattern.matcher(template);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            String key = m.group(1);
            String value = data.getOrDefault(key, "").toString();
            if (value != null && !value.isEmpty()) {
                //正则中的\$就代表$，字符串
                //由于$出现在replacement中时，表示对捕获组的反向引用
                value = value.replaceAll("\\$", "\\\\\\$");
                //System.out.println("value="+value);
                m.appendReplacement(sb, value);
            }
        }
        m.appendTail(sb);
        return sb.toString();
    }

    public static void main(String[] args) {
        /*SimpleTemplateEl ste=new SimpleTemplateEl("Hello,I am ${name}.I have  ${money}.");
        Map<String,Object> data=new HashMap<>();
        data.put("name","zwj");
        data.put("money","$120");
        System.out.println(ste.render(data));*/
        //单斜杠替换成双斜杠
        String str = "\\";
        System.out.println("before==" + str);
        //首先字符串\\\\\被转义后代表的实际字符串\\,在正则表达式中表示\,则匹配\
        //字符串\\\\\\\\转义后表示\\\\
        String str1 = str.replaceAll("\\\\", "\\\\\\\\");
        System.out.println("after=" + str1);

        String data="$1000";
        System.out.println(data.replaceAll("\\$","\\\\\\$"));

    }

}
